#include <iostream>
#include "Socket.hpp"
#include <time.h>
#include "Error.hpp"
#include "Log.hpp"
#include "unistd.h"
#include <string>
#include "Protocol.hpp"

std::string ip = "192.168.8.10";
uint16_t port = 8888;

using namespace std;
int main()
{
    Sock sock;
    sock.Socket();
    int cnt = 1;
    while (!sock.Connect(ip, port))
    {
        LOG(INFO, "重新建立连接，%d", cnt++);
        if (cnt == 5)
            exit(CONNECT_ERR);
        sleep(1);
    }
    LOG(INFO, "连接建立成功");

    // 连接建立成功后，进行通信
    std::string ops = "+-*/%";
    int op_len = ops.size();
    srand(time(nullptr));
    // 客户端，理应也要双缓冲区
    // 输入，输出缓冲区，
    // 但为了省事，我们就直接指读取一次，发送一次
    while (true)
    {
        // 构建请求
        Request req(rand() % 10, rand() % 10, ops[rand() % op_len]);
        // 序列化
        std::string req_body;
        req.Serialize(&req_body);
        // 添加报头
        Protocol::AddHeader(req_body);
        // 发送
        cout << "请求：" << endl;
        cout << req_body << endl;
        int n = send(sock.Fd(), req_body.c_str(), req_body.size(), 0);
        if (n == -1)
        {
            cout << "发送失败" << endl;
            continue;
        }
        char buf[1024];
        n = recv(sock.Fd(), buf, sizeof(buf) - 1, 0);
        if(n > 0)
        {
            cout << "响应：" << endl;
            buf[n] = 0;
            cout << buf << endl;
        }
        cout << "-----------------------" << endl;
    }
    return 0;
}